package com.leyou.cart.service;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.cart.interceptor.UserInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LeYouException;
import com.leyou.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Rose
 * @Date: 2021/4/11 19:38
 * @description ${description}
 * @version: 1.0.0
 */
@Slf4j
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String KEY_PREFIX = "cart:uid:";


    public void addCart(Cart cart) {

        // 获取登录用户
        UserInfo userInfos = UserInterceptor.getUserInfos();
        // key
        String key = KEY_PREFIX + userInfos.getId();
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(key);
        // hashKey
        String hashKey = cart.getSkuId().toString();
        // 判断当前购物车商品，是否存在
        if (operations.hasKey(hashKey)) {
            // 存在, 修改数量
            String json = operations.get(hashKey).toString();
            Cart cacheCart = JsonUtils.toBean(json, Cart.class);
            cacheCart.setNum(cacheCart.getNum() + cart.getNum());
            // 写回redis
            operations.put(hashKey, JsonUtils.tostring(cacheCart));
        } else {
            // 否, 新增
            operations.put(hashKey, JsonUtils.tostring(cart));
        }

    }


    /**
     * @return
     */
    public List<Cart> queryCartList() {
        // 获取登录用户
        UserInfo userInfos = UserInterceptor.getUserInfos();
        // key
        String key = KEY_PREFIX + userInfos.getId();
        // key

        if (!redisTemplate.hasKey(key)) {
            // key 不存在, 返回404
            throw new LeYouException(ExceptionEnum.CART_NOT_FOUND);
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(key);

        List<Object> values = operations.values();

        List<Cart> cartList = values.stream()
                .map(o -> JsonUtils.toBean(o.toString(), Cart.class))
                .collect(Collectors.toList());

        return cartList;
    }


    public void updateNum(Long skuId, Integer num) {
        // 获取登录用户
        UserInfo userInfos = UserInterceptor.getUserInfos();
        // key
        String key = KEY_PREFIX + userInfos.getId();
        // key

        if (!redisTemplate.hasKey(key)) {
            // key 不存在, 返回404
            throw new LeYouException(ExceptionEnum.CART_NOT_FOUND);
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(key);
        // 判断是否存在
        if (!operations.hasKey(skuId.toString())) {
            throw new LeYouException(ExceptionEnum.CART_NOT_FOUND);
        }
        // 查询购物车
        Cart cart = JsonUtils.toBean(operations.get(skuId.toString()).toString(), Cart.class);
        cart.setNum(num);

        // 写会redis 中
        operations.put(skuId.toString(), JsonUtils.tostring(cart));
    }

    public void deleteCart(Long skuId) {
        // 获取登录用户
        UserInfo userInfos = UserInterceptor.getUserInfos();
        // key
        String key = KEY_PREFIX + userInfos.getId();
        // key

        if (!redisTemplate.hasKey(key)) {
            // key 不存在, 返回404
            throw new LeYouException(ExceptionEnum.CART_NOT_FOUND);
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(key);
        // 判断是否存在
        if (!operations.hasKey(skuId.toString())) {
            throw new LeYouException(ExceptionEnum.CART_NOT_FOUND);
        }

        Long delete = operations.delete(skuId.toString());

        log.info("[购物车服务] 用户{} 删除了{} 商品！", JsonUtils.tostring(userInfos), skuId);
    }
}
